#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author：albert time:2021/9/2

import threading
import time
from HandDiscem import HandDiscem
from Game_2048 import Game2048


class Gesture2048Client:
    """
    手势2048游戏
    """

    def __init__(self):
        self.gesture_recognition_obj = HandDiscem()
        self.game_2048_obj = Game2048()

    def start(self):
        """
        启动, 启用两个子线程分别运行2048和手势识别
        """
        # 运行手势识别的线程
        thread_gesture = threading.Thread(target=self.gesture_recognition_obj.detect)
        thread_gesture.setDaemon(True)
        thread_gesture.start()
        # 运行2048游戏对象tkinter界面的线程
        thread_2048 = threading.Thread(target=self.game_2048_obj.run)
        thread_2048.setDaemon(True)
        thread_2048.start()
        # 循环获取手势识别对象的手势
        while True:
            if not self.game_2048_obj.active and not self.gesture_recognition_obj.active:
                # 若2048游戏页面和opencv界面均关闭，则程序结束
                break
            if self.gesture_recognition_obj.gesture:
                print(self.gesture_recognition_obj.gesture)
                if self.game_2048_obj.active:
                    self.game_2048_obj.gesture_handle(self.gesture_recognition_obj.gesture)
                else:
                    # tkinter的frame关闭之后不能再设置对象参数，设置会报错
                    print('2048页面已经关闭，手势不再生效')
                self.gesture_recognition_obj.gesture = ''
            time.sleep(2)

if __name__ == "__main__":
    gesture_game_client = Gesture2048Client()
    gesture_game_client.start()
